
import struct
from dataclasses import dataclass

@dataclass
class Frame_Head:
    head: int = 1152
    length: int = 0
    protocol: int = 0
    cmd: int = 0
    terminal: int = 0
    origin: int = 0


def package_frame():
    head = Frame_Head()
    head.length = 10
    head.protocol = 1
    head.cmd = 0x2
    head.terminal = 22
    head.origin = 33
    frame = struct.pack("<HHBBBB",head.head,head.length,head.protocol,head.cmd,head.terminal,head.origin)

    return frame

def unpackage_frame(frame):
    head = Frame_Head()
    # Error: struct.error: unpack requires a buffer of 8 bytes
    # head.head,head.length,head.protocol,head.cmd,head.terminal,head.origin = struct.unpack("<HHBBBB",frame)

    # 解决方法1: 按规则格式化
    head.head,head.length,head.protocol,head.cmd,head.terminal,head.origin = struct.unpack_from("<HHBBBB",frame, 0)
    # 解决方法2: 指定解析范围
    head.head,head.length,head.protocol,head.cmd,head.terminal,head.origin = struct.unpack("<HHBBBB",frame[0:8], 0)

    return head

if __name__ == "__main__":
    frame = package_frame()
    new_frame = unpackage_frame(frame+b'123456aabb')
    print(new_frame)

"""Running:
Frame_Head(head=1152, length=10, protocol=1, cmd=2, terminal=22, origin=33)

"""